
import { updateQueue } from "./component";
export default function addEvent(dom, eventType, handler) {
    // debugger
    // 1 document store
    let store = dom.store || (dom.store = {});
    // 2 创建映射表
    store[eventType] = handler;
    if (store[eventType]) {
        document[eventType] = emitEvent; // 将dom上的事件放到document上
    }
}
function emitEvent(event) {
    let { target, type } = event; // event事件对象
    console.log(target, type, event)
    let eventType = `on${type}`; //
    let { store } = target;
    let handler = store && store[eventType];

    // 合并事件对象
    let syntheticBaseEvent = createBaseEvent(event);

    updateQueue.isBatchData = true;
    handler && handler(syntheticBaseEvent);
    updateQueue.isBatchData = false;
    updateQueue.batchUpdate();
}

// 兼容
function createBaseEvent(event) {
    let syntheticBaseEvent = {};
    for (let key in event) {
        syntheticBaseEvent[key] = event[key];
    }
    // console.log(event.toString())
    syntheticBaseEvent.nativeEvent = event;
    syntheticBaseEvent.preventDefault = preventDefault;
    return syntheticBaseEvent;
}

// 处理默认事件
function preventDefault(event) {
    if (event) {
        window.event.returnValue = false;
    }
    if (event.preventDefault) {
        event.preventDefault();
    }
}